package pri.damai.xiaowu.usercenter.sysuser.application;

import cn.hutool.core.collection.CollectionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import pri.damai.xiaowu.common.core.exception.GlobalException;
import pri.damai.xiaowu.usercenter.common.constant.LoginType;
import pri.damai.xiaowu.usercenter.common.dto.LoginDTO;
import pri.damai.xiaowu.usercenter.common.dto.RoleDTO;
import pri.damai.xiaowu.usercenter.common.dto.UserDTO;
import pri.damai.xiaowu.usercenter.enums.SysUserResultEnum;
import pri.damai.xiaowu.usercenter.sysauth.entity.SysRole;
import pri.damai.xiaowu.usercenter.sysauth.service.SysRoleService;
import pri.damai.xiaowu.usercenter.sysuser.command.AddBaseUserCommand;
import pri.damai.xiaowu.usercenter.sysuser.entity.SysUser;
import pri.damai.xiaowu.usercenter.sysuser.service.SysUserMemberService;
import pri.damai.xiaowu.usercenter.sysuser.service.SysUserService;
import pri.damai.xiaowu.usercenter.sysuser.service.SysUserStaffService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 用户应用服务
 * @Desc
 * @Author yxf
 * @Date 2022/3/17 21:57
 * 但行好事，莫问前程。
 */
@Service
public class UserAppService {

    @Resource
    SysUserService userService;
    @Resource
    SysUserMemberService memberService;
    @Resource
    SysUserStaffService staffService;
    @Resource
    SysRoleService userRoleService;


    public UserDTO getUser(LoginDTO loginDTO) {

        UserDTO userDTO = null;

        if (Objects.equals(loginDTO.getLoginType(), LoginType.PHONE)) {

            SysUser sysUser = userService.getUserByPhone(loginDTO.getPhone());

            userDTO = this.covertToUserDTO(sysUser);

        } else {
            throw new GlobalException(SysUserResultEnum.LOGIN_FAIL.code(), SysUserResultEnum.LOGIN_FAIL.format("不支持的登录方式。"));
        }

        return userDTO;
    }

    public UserDTO createBaseUser(AddBaseUserCommand addBaseUserCommand) {

        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(addBaseUserCommand, sysUser);

        userService.saveUser(sysUser);

        return this.covertToUserDTO(sysUser);
    }

    public UserDTO covertToUserDTO(SysUser sysUser) {
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(sysUser, userDTO);
        userDTO.setUserId(sysUser.getId());
        List<SysRole> roles = userRoleService.getRoleByUserId(sysUser.getId());
        List<RoleDTO> roleDTOS = SysRole.covertToRoleDTO(roles);
        userDTO.setRoleList(roleDTOS);
        return userDTO;
    }

}
